'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function AddCustomerPage() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    phone2: '',
    phone2Purpose: '',
    wechat: '',
    wechatPurpose: '',
    qq: '',
    qqPurpose: '',
    whatsapp: '',
    whatsappPurpose: '',
    telegram: '',
    telegramPurpose: '',
    address: ''
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const router = useRouter();

  const autoFillForm = () => {
    const sampleCustomers = [
      {
        name: '李小明',
        email: `liming${Math.floor(Math.random() * 1000)}@example.com`,
        phone: '13800138001',
        address: '北京市朝阳区建国路88号'
      },
      {
        name: '王小红',
        email: `wanghong${Math.floor(Math.random() * 1000)}@example.com`,
        phone: '13900139002',
        address: '上海市浦东新区张江高科技园区'
      },
      {
        name: '张伟',
        email: `zhangwei${Math.floor(Math.random() * 1000)}@example.com`,
        phone: '13700137003',
        address: '广州市天河区体育西路123号'
      }
    ];
    
    const randomCustomer = sampleCustomers[Math.floor(Math.random() * sampleCustomers.length)];
    setFormData(randomCustomer);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/customers', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '创建失败');
      }

      const newCustomer = await response.json();
      
      router.push('/customers');
      router.refresh();
      
    } catch (error: any) {
      console.error('创建客户失败:', error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/customers" className="text-gray-600 hover:text-gray-900">
            ← 返回客户列表
          </Link>
          <h1 className="text-3xl font-bold">添加新客户</h1>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="bg-white rounded-lg shadow p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                姓名 *
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入客户姓名"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                邮箱 *
              </label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入邮箱地址"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                电话
              </label>
              <input
                type="tel"
                name="phone"
                value={formData.phone}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入电话号码"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                地址
              </label>
              <textarea
                name="address"
                value={formData.address}
                onChange={handleChange}
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入地址信息"
              />
            </div>
          </div>

          <div className="pt-6 border-t">
            <div className="flex space-x-3">
              <button
                type="submit"
                disabled={loading}
                className="px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                {loading ? '创建中...' : '创建客户'}
              </button>
              <button
                type="button"
                onClick={autoFillForm}
                className="px-6 py-3 bg-green-600 text-white rounded-md hover:bg-green-700"
              >
                自动填充
              </button>
              <Link
                href="/customers"
                className="px-6 py-3 bg-gray-600 text-white rounded-md hover:bg-gray-700"
              >
                取消
              </Link>
            </div>
          </div>
        </form>
      </div>

      <div className="mt-8 bg-yellow-50 border border-yellow-200 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-yellow-800 mb-2">填写说明</h3>
        <ul className="text-sm text-yellow-700 space-y-1">
          <li>• 标有 * 的字段为必填项</li>
          <li>• 邮箱地址必须是唯一的，不能重复</li>
          <li>• 电话和地址信息可选，建议填写完整信息</li>
          <li>• 客户创建后可以随时编辑和更新信息</li>
        </ul>
      </div>
    </div>
  );
}